package com.vichat.room.controller;

import com.vichat.common.constant.I18nConstant;
import com.vichat.common.exception.ViChatException;
import com.vichat.common.util.AES;
import com.vichat.common.util.I18NUtil;
import com.vichat.common.util.NumberUtils;
import com.vichat.common.util.StringToPropertiesConverter;
import com.vichat.common.vo.Grid;
import com.vichat.common.vo.Json;
import com.vichat.common.vo.PageFilter;
import com.vichat.room.entity.RoomBasic;
import com.vichat.room.entity.RoomMember;
import com.vichat.room.service.IRoomService;
import com.vichat.room.vo.RoomMemberVO;
import com.vichat.room.vo.RoomVO;
import com.vichat.user.controller.BaseController;
import com.vichat.user.entity.UserBasic;
import com.vichat.user.service.IUserService;
import com.vichat.user.vo.RequestParamsVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by ranjx on 2017/11/20.
 */
@Controller
@RequestMapping("/roomApi")
public class RoomApiController extends BaseController {
    ExecutorService tp = Executors.newCachedThreadPool();
    @Autowired
    HttpServletRequest request;
    @Autowired
    HttpServletResponse response;
    @Autowired
    private IUserService userService;
    @Autowired
    private IRoomService roomService;

    /**
     * 获取频道信息
     *
     * @param paramsVO
     * @return
     * @throws IOException
     */
    @RequestMapping("/getRooms")
    @ResponseBody
    public Grid getRooms(@RequestBody RequestParamsVO paramsVO) throws IOException {
        Grid grid = new Grid();
        try {
            if (NumberUtils.isNullOrZero(paramsVO.getUid())) {
//                throw new Exception("用户UID不能为空");
                String errorMsg = I18NUtil.getMessage("RoomApiController.getRooms.error_uIdNotEmpty", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_uIdNotEmpty, errorMsg);
            }
            if (NumberUtils.isNull(paramsVO.getVersion())) {
//                throw new Exception("版本号不能为空");
                String errorMsg = I18NUtil.getMessage("RoomApiController.getRooms.error_versionNotEmpty", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_versionNotEmpty, errorMsg);
            }

            UserBasic userBasicFDB = userService.getUserBasicByUid(paramsVO.getUid());
            if (userBasicFDB == null) {
//                throw new Exception("没有该用户信息，请确认UID参数");
                String errorMsg = I18NUtil.getMessage("RoomApiController.getRooms.error_userNotExist", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_userNotExist, errorMsg);
            }
            RoomBasic queryBean = new RoomBasic();
            queryBean.setOwnerId(paramsVO.getUid());
            queryBean.setPartyId(userBasicFDB.getPartyId());
            queryBean.setOrgCode(userBasicFDB.getOrgCode());
            queryBean.setVersion(paramsVO.getVersion());
            PageFilter pf = new PageFilter();
            pf.setPage(paramsVO.getPage());
            pf.setLimit(paramsVO.getRows());
            pf.setSort("version");
            pf.setOrder("asc");
            List<RoomBasic> roomList = roomService.queryRoomBasicsList(queryBean, pf);
            grid.setRows(roomList);
        } catch (ViChatException e) {
            e.printStackTrace();
            grid.setMsg(e.getMessage());
            grid.setI18nCode(e.getCode());
            grid.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setErrorMsg(e.getMessage());
            grid.setCode(-9);
        }
        return grid;
    }

    /**
     * 创建频道
     *
     * @param roomVO
     * @return
     */
    @RequestMapping("/createRoom")
    @ResponseBody
    public Json createRoom(@RequestBody RoomVO roomVO) {
        Json json = new Json();
        try {
            if (StringUtils.isBlank(roomVO.getName())) {
//                throw new Exception("频道名称不能为空");
                String errorMsg = I18NUtil.getMessage("RoomApiController.createRoom.error_roomNameNotEmpty", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_roomNameNotEmpty, errorMsg);
            }
            if (NumberUtils.isNullOrZero(roomVO.getStyle())) {
//                throw new Exception("频道类型不能为空");
                String errorMsg = I18NUtil.getMessage("RoomApiController.createRoom.error_roomTypeNotEmpty", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_roomTypeNotEmpty, errorMsg);
            }
            if (NumberUtils.isNull(roomVO.getExpireType())) {
//                throw new Exception("频道有效期不能为空");
                String errorMsg = I18NUtil.getMessage("RoomApiController.createRoom.error_roomExpireDateNotEmpty", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_expireDateNotEmpty, errorMsg);
            }
            if (roomVO.getUids().isEmpty()) {
//                throw new Exception("频道成员不能为空");
                String errorMsg = I18NUtil.getMessage("RoomApiController.createRoom.error_uidsNotEmpty", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_roomUidsNotEmpty, errorMsg);
            }
            if (NumberUtils.isNullOrZero(roomVO.getUid())) {
//                throw new Exception("用户UID不能为空");
                String errorMsg = I18NUtil.getMessage("RoomApiController.createRoom.error_uidNotEmpty", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_uIdNotEmpty, errorMsg);
            }
            UserBasic userBasic = userService.getUserBasicByUid(roomVO.getUid());
            if (userBasic == null) {
//                throw new Exception("当前民警信息不存在");
                String errorMsg = I18NUtil.getMessage("RoomApiController.createRoom.error_userNotExist", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_userNotExist, errorMsg);
            }
            roomVO.setPartyId(userBasic.getPartyId());
            roomVO.setOrgId(userBasic.getOrgId());
            roomVO.setOrgCode(userBasic.getOrgCode());
            RoomBasic roomBasicFDB = roomService.createRoom2Member(roomVO);
            if (roomBasicFDB != null) {
                roomService.updateRoomBasicVersion(roomBasicFDB.getRid());

                if (!roomVO.getUids().isEmpty() && roomBasicFDB != null) {
                    for (long uid : roomVO.getUids()) {
                        roomService.updateRoomMemberVersion(uid,roomBasicFDB.getRid());
                    }
                }
            }
            HashMap map = new HashMap();
            map.put("rid", roomBasicFDB.getRid());
            map.put("name", roomBasicFDB.getName());
            json.setObj(map);
            json.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 批量删除用户信息
     * batchDelUser
     *
     * @param queryParam
     * @return
     */
    @RequestMapping("/delRoomMember")
    @ResponseBody
    public Json delRoomMember(@RequestBody RoomMemberVO queryParam) {
        Json json = new Json();
        try {
            String token = AES.decrypt(queryParam.getToken());
            Properties properties = StringToPropertiesConverter.convert(token.replaceAll(",", "\n"));
            String uidInToken = properties.getProperty("uid");
            if (!StringUtils.equals(uidInToken, String.valueOf(queryParam.getUid()))) {
                throw new Exception("token is illegal");
            }

            UserBasic userBasicFDB = userService.getUserBasicByUid(queryParam.getUid());
            if (userBasicFDB == null) {
                throw new Exception("User Data Error");
            }

            long rid = queryParam.getRid();
            RoomBasic roomBasic = roomService.getRoomBasicByRid(rid);
            if (queryParam.getUids() != null && !queryParam.getUids().isEmpty()) {
                for (Long uid : queryParam.getUids()) {
                    roomService.delRoomMemberLogically(roomBasic.getRid(), uid);
                    roomService.updateRoomMemberVersion(uid,roomBasic.getRid());
                }
            }
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 添加频道用户
     *
     * @param queryParam
     * @return
     */
    @RequestMapping("/addRoomMember")
    @ResponseBody
    public Json addRoomMember(@RequestBody RoomMemberVO queryParam) {
        Json json = new Json();
        try {
            String token = AES.decrypt(queryParam.getToken());
            Properties properties = StringToPropertiesConverter.convert(token.replaceAll(",", "\n"));
            String uidInToken = properties.getProperty("uid");
            if (!StringUtils.equals(uidInToken, String.valueOf(queryParam.getUid()))) {
                throw new Exception("token is illegal");
            }

            UserBasic userBasicFDB = userService.getUserBasicByUid(queryParam.getUid());
            if (userBasicFDB == null) {
                throw new Exception("User Data Error");
            }

            long rid = queryParam.getRid();
            RoomBasic roomBasic = roomService.getRoomBasicByRid(rid);
            if (roomBasic != null && roomBasic.getPartyId().longValue() == userBasicFDB.getPartyId().longValue()) {//登录用户和频道是一个企业下的
                if (queryParam.getUids() != null && queryParam.getUids().size() > 0) {
                    for (long uid : queryParam.getUids()) {
                        if (uid > 0) {
                            RoomMember hasMember = roomService.getRoomMember(queryParam.getRid(), uid);
                            if (hasMember == null) {
                                UserBasic userFDB = userService.getUserBasicByUid(uid);
                                if (userFDB.getPartyId().longValue() == userBasicFDB.getPartyId().longValue()) {//成员和登录用户也必须是一个企业下
                                    RoomMember member = new RoomMember();
                                    member.setRid(queryParam.getRid());
                                    member.setUid(uid);
                                    member.setAdminGrade(5L);
                                    member.setPriority(2L);
                                    member.setTimelen(120L);
                                    member.setUserName(userFDB.getUserName());
                                    roomService.saveRoomMember(member);

                                    roomService.updateRoomMemberVersion(uid,member.getRid());
                                }
                            }
                        }
                    }
                }
            }
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 删除频道
     *
     * @param queryParam
     * @return
     */
    @RequestMapping("/deleteRoom")
    @ResponseBody
    public Json deleteRoom(@RequestBody RoomMemberVO queryParam) {
        Json json = new Json();
        try {
            String token = AES.decrypt(queryParam.getToken());
            Properties properties = StringToPropertiesConverter.convert(token.replaceAll(",", "\n"));
            String uidInToken = properties.getProperty("uid");
            if (!StringUtils.equals(uidInToken, String.valueOf(queryParam.getUid()))) {
                throw new Exception("token is illegal");
            }

            UserBasic userBasicFDB = userService.getUserBasicByUid(queryParam.getUid());
            if (userBasicFDB == null) {
                throw new Exception("User Data Error");
            }

            long rid = queryParam.getRid();
            RoomBasic roomBasic = roomService.getRoomBasicByRid(rid);
            if (roomBasic != null && roomBasic.getPartyId().longValue() == userBasicFDB.getPartyId().longValue()) {//登录用户和频道是一个企业下的
                if (userBasicFDB.getUid().longValue() == roomBasic.getOwnerId().longValue()) {
                    roomService.delRoomBasic(rid);
                    roomService.updateRoomBasicVersion(rid);
                    json.setSuccess(true);
                } else {
                    throw new Exception("Not enough permission");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 退出频道
     *
     * @param queryParam
     * @return
     */
    @RequestMapping("/quitRoom")
    @ResponseBody
    public Json quitRoom(@RequestBody RoomMemberVO queryParam) {
        Json json = new Json();
        try {
            String token = AES.decrypt(queryParam.getToken());
            Properties properties = StringToPropertiesConverter.convert(token.replaceAll(",", "\n"));
            String uidInToken = properties.getProperty("uid");
            if (!StringUtils.equals(uidInToken, String.valueOf(queryParam.getUid()))) {
                throw new Exception("token is illegal");
            }

            UserBasic userBasicFDB = userService.getUserBasicByUid(queryParam.getUid());
            if (userBasicFDB == null) {
                throw new Exception("User Data Error");
            }

            long rid = queryParam.getRid();
            RoomMember roomMembers = roomService.getRoomMember(rid, userBasicFDB.getUid());
            if (roomMembers != null) {//只能自己退出频道
                roomService.delRoomMemberLogically(rid, userBasicFDB.getUid());
                roomService.updateRoomMemberVersion(userBasicFDB.getUid(),rid);
            }
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }
}
